package es.udc.fic.hamNeggs.web;

import org.apache.log4j.Logger;

import es.udc.fic.hamNeggs.dao.InputMeeting;
import es.udc.fic.hamNeggs.dao.InputUser;
import es.udc.fic.hamNeggs.manager.MeetingCommentManager;
import es.udc.fic.hamNeggs.manager.MeetingManager;
import es.udc.fic.hamNeggs.manager.ProjectManager;
import es.udc.fic.hamNeggs.manager.UserManager;
import es.udc.fic.hamNeggs.pojo.Meeting;
import es.udc.fic.hamNeggs.pojo.Meeting.MeetingType;
import es.udc.fic.hamNeggs.pojo.MeetingComment;
import es.udc.fic.hamNeggs.pojo.Works;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Enumeration;

/**
 * Servlet implementation class MeetingDetails
 */
public class MeetingDetails extends HttpServlet {
    private static final long   serialVersionUID = 1L;
    private final static Logger LOG              = Logger.getLogger(MeetingDetails.class.getName());

    /**
     * @see HttpServlet#HttpServlet()
     */
    public MeetingDetails() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
        final ProjectManager prjmng = new ProjectManager();
        final HttpSession session = request.getSession(true);

        final Long myUser = (Long) session.getAttribute("user");

        final Long myProject = (Long) session.getAttribute("project");
        final ArrayList<InputUser> users = new ArrayList<InputUser>();

        for (final Works w : prjmng.getProject(new Long(myProject)).getWorker()) {
            if (w.getUser().getId().doubleValue() != myUser.doubleValue()) {
                final InputUser u = new InputUser();
                u.setUser(w.getUser());
                users.add(u);
            }
        }

        request.setAttribute("users", users);

        if ((request.getParameter("id") != null && request.getParameter("id") != "") || (request.getAttribute("mtgid") != null && request.getAttribute("mtgid").toString() != "")) {
            final MeetingManager mtgmng = new MeetingManager();
            Meeting mtg = null;
            if (request.getParameter("id") != null)
                mtg = mtgmng.getMeeting(new Long(request.getParameter("id")));
            else if (request.getAttribute("mtgid") != null)
                mtg = mtgmng.getMeeting(new Long(request.getAttribute("mtgid").toString()));
            final InputMeeting inputMeeting = new InputMeeting();
            inputMeeting.setMeeting(mtg);
            request.setAttribute("comments", inputMeeting.getComments());
            request.setAttribute("selectMeeting", inputMeeting);
            mtgmng.close();
        }

        prjmng.close();
        request.getRequestDispatcher("/meeting_detail.jsp").forward(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
        final HttpSession session = request.getSession(true);

        final Long myUser = (Long) session.getAttribute("user");
        final Long myProject = (Long) session.getAttribute("project");

        final MeetingManager mtgmng = new MeetingManager();
        final UserManager usrmng = new UserManager();
        final ProjectManager prjmng = new ProjectManager();
        final MeetingCommentManager cmtmng = new MeetingCommentManager();

        try {
            switch (request.getParameter("action")) {
                case "Add":
                    final InputMeeting meeting = new InputMeeting();
                    final ArrayList<String> atendees = new ArrayList<String>();

                    for (final String a : request.getParameterValues("stringAttendees"))
                        atendees.add(a);

                    meeting.setAttendees(atendees);

                    if (request.getParameter("date") != null)
                        meeting.setDate(request.getParameter("date"));
                    if (request.getParameter("type") != null)
                        meeting.setType(request.getParameter("type"));

                    final Meeting newMeeting = meeting.toMeeting();

                    if (newMeeting != null) {
                        newMeeting.setMeetingLeader(usrmng.getUser(myUser));
                        newMeeting.setProject(prjmng.getProject(myProject));
                        mtgmng.saveMeeting(newMeeting);
                    }
                    break;
                case "Update":
                    final Meeting oldMeetingu = mtgmng.getMeeting(new Long(request.getParameter("mtgid")));

                    if (request.getParameterValues("stringAttendees") != null) {
                        oldMeetingu.clearAttendees();
                        for (final String a : request.getParameterValues("stringAttendees")) {
                            oldMeetingu.setAttendee(usrmng.getUser(new Long(a)));
                        }
                        oldMeetingu.setAttendee(usrmng.getUser(new Long(myUser)));
                        usrmng.close();
                    }

                    if (request.getParameter("date") != null)
                        oldMeetingu.setDate(Date.valueOf(request.getParameter("date")));
                    if (request.getParameter("type") != null)
                        oldMeetingu.setType(MeetingType.valueOf(request.getParameter("type")));

                    mtgmng.updateMeeting(oldMeetingu);
                    break;
                case "AddComment":
                    final String comment = request.getParameter("cmt");
                    final Meeting mtg = mtgmng.getMeeting(new Long(request.getParameter("mtgid")));

                    final MeetingComment mtgcmt = new MeetingComment();

                    mtgcmt.setComment(comment);
                    mtgcmt.setMeeting(mtg);
                    cmtmng.saveMeetingComment(mtgcmt);
                    break;
                case "DeleteComment":
                    final String cmtid = request.getParameter("cmtid");
                    final MeetingComment cmt = cmtmng.getMeetingComment(new Long(cmtid));
                    cmtmng.deleteMeetingComment(cmt);
                    break;
                default:
                    break;

            }
        } catch (Exception e) {
            String error = "[";
            Enumeration<String> names = request.getParameterNames();
            while (names.hasMoreElements()) {
                final String paramName = names.nextElement();
                final String paramValue = request.getParameter(paramName);
                error = error.concat(paramName + ":" + paramValue + "|");
            }
            error = error.concat("]");
            LOG.error("Error while executing action: " + request.getParameter("action")
                    + " with params: " + error + "\n"
                    , e);
        }

        usrmng.close();
        mtgmng.close();
        prjmng.close();

        request.setAttribute("mtgid", request.getParameter("mtgid"));
        this.doGet(request, response);
    }
}
